//app.js
var eventBus = require('utils/event.js')
var util = require('utils/util.js')
var im = require('./utils/im.js')
import cache from './utils/cache.js'
import filter from 'utils/filter'
filter.install()
// import { observable, autorun } from 'utils/mobx4.1.js';
App({
  /**
   *  app登录方法，
   *  传入user对象，{userName:"",password:""}，promise返回用户信息
   * @param {Boolean} ismd5 - 是否需要md5加密 false 为加密，true为不加密
   */
  login(user, ismd5){
    var _resolve, _reject;
    if (!user)
      throw new Error('请传入user对象{userName:"",password:""}')
    var params = {}
    params.userName = user.userName
    if (!ismd5){
      params.password = util.md5(user.password)
    }else{
      params.password = user.password
    }
    var url = wx.envConfig.host + '/user/login?params=' + JSON.stringify(params)
    wx.request({
      url: url,
      method: 'GET',
      success:  (res)=>{
        if (res.data.error_code == "Y10000"){
          console.log('res```login', res)
          this.appUserInfo = res.data.datas
          wx.setStorageSync("cookiez", this.appUserInfo.cookiez)
          wx.setStorageSync("userInfo", this.appUserInfo)
          var data = JSON.parse(JSON.stringify(res.data.datas))
          _resolve(data)

        }else{
          wx.setStorageSync("userInfo", "")
          wx.setStorageSync("cookiez", "")
          _reject(this.appUserInfo)
        }
        // if (res && res.data && res.data.datas && res.data.datas.code === 'Y10000') {
        //   // 获取用户信息->首页
        //   this.getSetting()
        // } else {
        //   // 引导用户绑定手机->注册完成->引导用户认证->认证完成
        //   wx.navigateTo({ url: '/pages/mine/regist/regist' })
        // }
        // 暂时写死token
        // this.globalData && (this.globalData.token = 'abcdefghijklmn123456')
        // wx.navigateTo({ url: '/pages/home/main/main' })
      },
      fail: function (res) {
        wx.setStorageSync("cookiez", "")
        wx.setStorageSync("userInfo", "")
        _reject(res)
       },
      complete: function (res) { },
    })
    return new Promise((resolve,reject)=>{
      _resolve = resolve
      _reject = reject
    })
  },
  /**
   * 获取用户信息
   * @param {Boolean} islocal - 绕过获取本地参数 为true时 不考虑本地数据
   * */
  getAppUserInfo: function (islocal) {
    let ApiuserInfo = '/user/info'
    return new Promise((resolve, reject) => {
      // resolve(this.appUserInfo)
      let token = wx.getStorageSync('cookiez')
      if (token && token != 'undefined' && token != "code") {
        if (this.appUserInfo && !islocal) {
          resolve(this.appUserInfo)
        } else {
          wx.request({
            method: 'get',
            url: wx.envConfig.host + ApiuserInfo + '?cookiez=' + token,
            success:  (res, origin) => {
              if (res.data.error_code == "Y10000") {
                this.appUserInfo = res.data.datas
                wx.setStorageSync("userInfo", this.appUserInfo)
                var data = JSON.parse(JSON.stringify(res.data.datas))
                resolve(data)
              } else {
                wx.setStorageSync("userInfo", "")
                wx.setStorageSync("cookiez", "")
                reject(res)
              }
            },
            fail: function (res) {
              wx.setStorageSync("cookiez", "")
              wx.setStorageSync("userInfo", "")
              reject(res)
            },
          })
        }
      } else {
        wx.showModal({
          title: '提示',
          content: '您需要登录您的个人信息',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/mine/regist/regist'
              })
            }
          }
        })
        // throw new Error('没有登录')
      }
    })
  },
  /**
   * 判断用户是否登录
   * 如果没有登录就跳转填写手机号页面
   * */
  loginQuery:function(isBack){ // isBack是否需要返回去
    if (!this.appUserInfo||!this.appUserInfo.id){
      if (cache.get('canShowModal')) {
        wx.showModal({
          title: '温馨提示',
          content: '您还未登录,现在登录吗?',
          cancelText: '让我想想',
          confirmText: '立即前往',
          success: function(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/mine/regist/regist'
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
              if (isBack) {
                console.log('返回')
                wx.switchTab({
                  url: '/pages/home/main/main'
                })
              }
            }
          }
        })
      }
      return false
    } else {
      return true
    }
  },
  /*
   * 根据上传信息获取图片的实际id
   */
  fileBinding: function(data) {
    return new Promise((resolve, reject) => {
      if (data && data.id) {
        wx.request({
          url: wx.envConfig.adminHost+'/serviceCommon/fileBinding',
          method: 'POST',
          data: data,
          success: (res) => {
            if (res.data.error_code === 'Y10000') {
              resolve(res)
            } else {
              throw new Error('获取新id返回值error_code异常')
            }
          },
          fail: (err) => {
            if (err) {
              throw err
            }
          }
        })
      } else {
        throw new Error('返回图片上传参数有误')
      }
    })
  },
  onLaunch: function () {
    // 展示本地存储能力
    // 清理所有本地缓存
    wx.clearStorage();
    wx.eventBus = eventBus;
    wx.envConfig = this.globalData.env[this.globalData.env.mode];
    // var params = {
    //   'userName': '13249726272',
    //   'password': 'qq123456'
    // }
    // this.login(params).then((res) => {
    //   console.log('res', res)
    //   this.getAppUserInfo().then((info) => {
    //     console.log("getAppUserInfo", info)
    //   })
    // })

    // 登录
    wx.showLoading({
      title:'加载中...',
      mask:true
    })
    wx.hideTabBar();
    wx.login({
      success: res => {
        console.log('微信登录信息',res)
        this.globalData.code = res.code
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          let url = wx.envConfig.host + '/user/wxAutoLogin?params=' + JSON.stringify({code:res.code,type: 1})  // url可变更,需后端提供
          wx.request({
            url:url,
            method:'GET',
            success:  (res)=> {
              console.log(res.data)
              if (res && res.data) {
                console.log('res````bycode', res)
                this.globalData.openid = res.data.datas.open_id
                if (res.data.error_code === 'Y10000' && res.data.datas.open_id && res.data.datas.cookiez) {
                  // 获取用户信息->首页
                  // this.getSetting()
                  wx.setStorageSync("cookiez", res.data.datas.cookiez)
                  this.login(res.data.datas,true).then((info) => {
                    wx.hideLoading()
                    wx.showTabBar()
                    wx.eventBus.trigger('loginSuccess', info)
                    console.log("自动登录----", info)
                  },(re)=>{
                    wx.hideLoading()
                    wx.showTabBar()
                  }).catch(e => {
                    console.log('err',e);
                    wx.showTabBar()
                  })
                } else {
                  wx.showTabBar()
                  wx.hideLoading()
                  // 引导用户绑定手机->注册完成->引导用户认证->认证完成
                  // wx.navigateTo({ url: '/pages/mine/regist/regist' })
                }
              }
            }
          })
        } else {
          wx.hideLoading()
          console.log('登录失败' + res.errMsg)
        }
      },
      complete: function(res) {
        console.log(res)
        wx.hideLoading()
        // wx.navigateTo({ url: '/pages/mine/regist/regist' })
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              console.log('this.globalData', this.globalData)

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  appUserInfo: null,
  globalData: {
    userInfo: {
      'id': 206,
      'userName': '13113864577',
      'password': 'fanjunlin123',
      'token': 'abcdefghijklmn123456'
    },
    code:'',
    openid:'',
    env:{
      mode:'production',
      dev: {
        host: 'http://192.168.1.233:8080/yishuju-app',
        imgHost: 'http://192.168.1.233:8080/uploadFile',
        orderListImgHost: 'http://192.168.1.233:8080/yishuju-admin/file/getNew/',
        adminHost: 'http://192.168.1.233:8080/yishuju-admin',
        pcHost: 'http://192.168.1.233:8080/yishuju-pc/',
        adminHostView: 'http://192.168.1.233:8080',
        visitRoute: 'https://testpc.1sju.com',
        filePath: 'https://file.1sju.com/'
      },
      testing: {
        h5host: 'https://testapp.1sju.com/yishuju-adminh5',
        host: 'https://testapp.1sju.com/yishuju-app',
        orderListImgHost: 'https://testadmin.1sju.com/yishuju-admin/file/getNew/',
        imgHost: 'https://testadmin.1sju.com/uploadFile',
        adminHost: 'https://testadmin.1sju.com/yishuju-admin',
        adminHostView: 'https://testadmin.1sju.com',
        pcHost: 'https://testpc.1sju.com/yishuju-pc/',
        visitRoute: 'https://testpc.1sju.com',
        filePath: 'https://dataup.1sju.com/'
      },
      production: {
        host: 'https://app.1sju.com/yishuju-app',
        orderListImgHost: 'https://admin.1sju.com/yishuju-admin/file/getNew/',
        imgHost: 'https://admin.1sju.com/uploadFile',
        adminHost: 'https://admin.1sju.com/yishuju-admin',
        adminHostView: 'https://admin.1sju.com',
        pcHost: 'https://www.1sju.com/yishuju-pc/',
        visitRoute: 'https://www.1sju.com',
        filePath: 'https://file.1sju.com/'
      },
      spare: {
        host: 'https://spareapp.1sju.com/yishuju-app',
        orderListImgHost: 'https://spareadmin.1sju.com/yishuju-admin/file/getNew/',
        imgHost: 'https://spareadmin.1sju.com/uploadFile',
        adminHost: 'https://spareadmin.1sju.com/yishuju-admin',
        adminHostView: 'https://spareadmin.1sju.com',
        pcHost: 'https://sparepc.1sju.com/yishuju-pc/',
        visitRoute: 'https://sparepc.1sju.com',
        filePath: 'https://dataup.1sju.com/'
      },
    }
  }
})